package service

import (
	"strings"
	"tool/model"
	"tool/utils"

	"gitee.com/xuesongtao/protoc-go-valid/log"
	"gitee.com/xuesongtao/protoc-go-valid/valid"
)

// GetEnc2DecRes 获取加/解密结果
func GetEnc2DecRes(s string, f symCryptFunc) string {
	buf := new(strings.Builder)
	strSplit := strings.Split(s, ",")
	for _, in := range strSplit {
		out, err := f(in)
		if err != nil {
			log.Infof("crypt is failed, inStr: %s, err: %v", out, err)
			continue
		}
		tmpStr := "in: " + in + ";  out: " + utils.FontBold(out) + "\n"
		buf.WriteString(tmpStr)
	}
	return buf.String()
}

func Enc(req *model.Enc2DecReq) *model.RespData {
	log.Infof("Enc req: %+v", req)
	if err := valid.ValidateStruct(req); err != nil {
		log.Error("valid is failed, err: ", err)
		return model.GetResp(err.Error(), 1)
	}

	encFunc := SymEncrypt2Func
	if req.Type == 1 {
		encFunc = SymEncrypt1Func
	}
	return model.GetResp(GetEnc2DecRes(req.Data, encFunc))
}

func Dec(req *model.Enc2DecReq) *model.RespData {
	log.Infof("Dec req: %+v", req)
	if err := valid.ValidateStruct(req); err != nil {
		log.Error("valid is failed, err: ", err)
		return model.GetResp(err.Error(), 1)
	}

	decFunc := SymDecrypt2Func
	if req.Type == 1 {
		decFunc = SymDecrypt1Func
	}
	return model.GetResp(GetEnc2DecRes(req.Data, decFunc))
}
